import time
import bluetooth
from micropython import const
import machine
from machine import UART

# 配置串口 (TX: GPIO2, RX: GPIO3)
uart = UART(1, baudrate=115200, tx=2, rx=3)

# BLE常量定义
_IRQ_CENTRAL_CONNECT = const(1)
_IRQ_CENTRAL_DISCONNECT = const(2)
_IRQ_GATTS_WRITE = const(3)

_UART_UUID = bluetooth.UUID('6E400001-B5A3-F393-E0A9-E50E24DCCA9E')
_UART_TX = (bluetooth.UUID('6E400003-B5A3-F393-E0A9-E50E24DCCA9E'), bluetooth.FLAG_READ | bluetooth.FLAG_NOTIFY,)
_UART_RX = (bluetooth.UUID('6E400002-B5A3-F393-E0A9-E50E24DCCA9E'), bluetooth.FLAG_WRITE,)
_UART_SERVICE = (_UART_UUID, (_UART_TX, _UART_RX,),)

_ADV_NAME = 'TGAM'  # 蓝牙名称
_BLE_PASSWORD = '123456'  # 蓝牙密码


class BLEUART:
    def __init__(self, name):
        self.name = name
        self.ble = bluetooth.BLE()
        self.ble.active(True)
        self.ble.irq(self._irq)
        self.register()
        self.callback = None
        self.connected = False
        self.password_verified = False

    def _irq(self, event, data):
        # 处理连接事件
        if event == _IRQ_CENTRAL_CONNECT:
            conn_handle, _, _ = data
            self.connected = True
            print('设备已连接')

        # 处理断开连接事件
        elif event == _IRQ_CENTRAL_DISCONNECT:
            conn_handle, _, _ = data
            self.connected = False
            self.password_verified = False
            print('设备已断开连接')
            # 重新开始广播
            self.advertise()

        # 处理写入事件
        elif event == _IRQ_GATTS_WRITE:
            conn_handle, value_handle = data
            if value_handle == self.rx_handle:
                data = self.ble.gatts_read(self.rx_handle)
                if not self.password_verified:
                    # 验证密码
                    if data.decode().strip() == _BLE_PASSWORD:
                        self.password_verified = True
                        self.ble.gatts_notify(conn_handle, self.tx_handle, b'OK')
                        print('密码验证成功')
                    else:
                        self.ble.gatts_notify(conn_handle, self.tx_handle, b'ERROR')
                        print('密码验证失败')
                else:
                    # 密码验证通过，处理脑电数据
                    if self.callback:
                        self.callback(data)

    def register(self):
        # 注册UART服务
        services = (_UART_SERVICE,)
        ((self.tx_handle, self.rx_handle,),) = self.ble.gatts_register_services(services)

    def advertise(self):
        # 构建广播数据
        name = bytes(self.name, 'utf-8')
        adv_data = bytearray(2 + len(name)) + b'\x01\x06'  # 0x06表示支持BLE
        adv_data[0] = 1 + len(name)
        adv_data[1] = 0x09
        adv_data[2:] = name

        # 开始广播
        self.ble.gap_advertise(100, adv_data)
        print('开始蓝牙广播，名称:', self.name)

    def send(self, data):
        # 发送数据
        self.ble.gatts_notify(0, self.tx_handle, data)

    def set_callback(self, callback):
        # 设置数据接收回调
        self.callback = callback


# 数据缓冲区和计数器
eeg_buffer = []
buffer_counter = 0


def handle_eeg_data(data):
    """处理接收到的脑电数据"""
    global eeg_buffer, buffer_counter

    try:
        values = data.decode().strip().split(',')
        for val in values:
            # 累加数据到缓冲区
            eeg_buffer.append(val)
            buffer_counter += 1

            # 每收到512个数据（1秒的数据量）通过串口发送
            if buffer_counter >= 512:
                # 拼接成字符串发送
                uart.write(','.join(eeg_buffer[:512]) + '\n')
                # 清空缓冲区
                eeg_buffer = eeg_buffer[512:]
                buffer_counter -= 512

    except Exception as e:
        print('数据处理错误:', e)


# 初始化BLE
ble_uart = BLEUART(_ADV_NAME)
ble_uart.set_callback(handle_eeg_data)
ble_uart.advertise()

# 主循环
while True:
    if not ble_uart.connected:
        # 每5秒检查一次连接状态
        time.sleep(5)
    else:
        # 已连接状态，短时间休眠
        time.sleep(0.1)
    # 喂狗
    machine.watchdog_reset()
